<template>
  <div>
    <div v-for="(item,index) in commentList" :key="index">
      <!-- 评论发布者和发布时间 -->
      <div>
        {{item.name}} on {{item.time}}
        <span
          v-if="item.children"
          @click="setFlod(index)"
        >{{`[...${item.children.length} more]`}}</span>
        <span v-else @click="setFlod(index)">[...]</span>
      </div>
      <!-- ------- -->
      <!-- 评论的内容和子评论 -->
      <div v-if="flod[index]">
        <div class="content">{{item.content}}</div>
        <div class="reply" @click="setReplyInput(index)">reply</div>
        <div v-if="replyInput[index]">
          <textarea v-model="commentContent"></textarea>
          <div>
            <button @click="sendComment(item.id,index)">add comment</button>
          </div>
        </div>
        <div class="children">
          <Comment v-if="item.children" :commentList="item.children"></Comment>
        </div>
      </div>
      <!-- ------ -->
    </div>
  </div>
</template>

<script>
import { addReplyComment } from "../utils/commentController";
export default {
  name: "Comment",
  //当发送评论后调用祖先组件的reload获取新的评论列表
  inject: ["reload"],
  data() {
    return {
      //评论是否折叠的数组
      flod: [],
      //评论框是否显示的数组
      replyInput: [],
      //评论内容
      commentContent: ""
    };
  },
  props: {
    commentList: Array
  },
  methods: {
    //设置该评论是否折叠
    setFlod(index) {
      const flag = !this.flod[index];
      this.$set(this.flod, index, flag);
    },
    //设置评论窗口是否展示
    setReplyInput(index) {
      const flag = !this.replyInput[index];
      this.$set(this.replyInput, index, flag);
    },
    //发表评论
    sendComment(replyCommentId, index) {
      let content = this.commentContent;
      addReplyComment(replyCommentId, content);
      //通过调用祖先组件注入的reload方法，使评论列表更新
      this.reload();
      //关闭评论框
      this.setReplyInput(index);
    }
  },
  created() {}
};
</script>

<style>
.children {
  margin-left: 30px;
}
.reply {
  text-decoration: underline;
}
</style>